package com.liangtian.mdm.dm.group.controller;

import com.alibaba.fastjson.JSON;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.utils.ResultObject;
import com.liangtian.mdm.dm.common.util.GroupUtil;
import com.liangtian.mdm.dm.group.model.AttrGroup;
import com.liangtian.mdm.dm.group.service.AttrGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RequestMapping("/group")
@Controller
public class AttrGroupController extends BaseController {

    @Autowired
    private AttrGroupService attrGroupService;

    @RequestMapping(value = "/queryAttributeList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public String queryAttributeList(@RequestParam String modelId) {

        List<AttrGroup> attrList = attrGroupService.queryAttributeList(modelId);
        //System.out.println("---------group--------"+attrList.size());

        Map<String, List<AttrGroup>> groupList = GroupUtil.groupOrder(attrList, new GroupUtil.GroupBy<String>() {
            @Override
            public String groupby(Object obj) {
                AttrGroup group = (AttrGroup) obj;
                //System.out.println(group.getPosition().toString()+"♀"+String.valueOf(group.getGroupId())+"♀"+group.getGroupName()+"♀"+group.getIsDefaultView());
                return group.getPosition().toString() + "♀" + String.valueOf(group.getGroupId()) + "♀" + group.getGroupName() + "♀" + group.getIsDefaultView();

            }
        });

        //System.out.println(JSON.toJSONString(groupList));
        return JSON.toJSONString(groupList);
    }

    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public ResultObject saveOrUpdate(HttpServletRequest request) {

        String jsonStr = request.getParameter("data");
        List<AttrGroup> items = JSON.parseArray(jsonStr, AttrGroup.class);

        //System.out.println("------saveOrUpdate-----"+items.size());
        boolean b = attrGroupService.saveOrUpdateRelation(items);
        int f = b ? 1 : 0;
        ResultObject result = new ResultObject(f, "更新成功", "更新失败");
        return result;
    }

}
